package leetcode.weekly.week302;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;

//Solution4Test
public class Solution4 {

	public int minOperations(int[] nums, int[] numsDivide) {
		Map<Integer, Integer> map1 = new HashMap<>();
		for (int i = 0; i < nums.length; i++) {
			int num = nums[i];
			int cnt = map1.getOrDefault(num, 0);
			map1.put(num, cnt + 1);
		}
		int[][] ns = new int[map1.size()][];
		int p = 0;
		PriorityQueue<int[]> queue = new PriorityQueue<>((a, b) -> a[0] - b[0]);
		for (Map.Entry<Integer, Integer> e : map1.entrySet()) {
			int num = e.getKey(), cnt = e.getValue();
			queue.add(new int[] { num, cnt });
		}
		Set<Integer> set = new HashSet<>();
		for (int i = 0; i < numsDivide.length; i++) {
			set.add(numsDivide[i]);
		}
		List<Integer> list = new ArrayList<>(set);
		Collections.sort(list);
		int ans = 0;
		while (!queue.isEmpty()) {
			int[] cur = queue.poll();
			int num = cur[0], cnt = cur[1];
			if (this.check(list, num)) {
				return ans;
			}
			ans += cnt;
		}
		return -1;

	}

	private boolean check(List<Integer> list, int num) {
		for (int i = 0; i < list.size(); i++) {
			if(list.get(i)%num!=0) {
				return false;
			}
		}
		return true;
	}

}
